package com.example.work8_1.Service;


import com.example.work8_1.DAO.RoleReposiry;
import com.example.work8_1.DAO.UserReposiry;
import com.example.work8_1.entity.Role;
import com.example.work8_1.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.transaction.Transactional;
import java.util.Optional;

@Service
public class UserService {

    @Autowired
    UserReposiry userReposiry;
//    @Autowired
//    PasswordEncoder passwordEncoder;
    @Autowired
    RoleReposiry roleReposiry;


    @Transactional
    @PostConstruct
    //初始化
    public void init()
    {
        Optional<Role> r = roleReposiry.findById("Admin");
        Role role;
        if(!r.isPresent())
        {
            role = new Role();
            role.setName("Admin");
            role.getAuthorities().add("Administration");
            roleReposiry.save(role);
        }
        else
        {
            role = r.get();
        }

        Optional<User> u = userReposiry.findById("admin");
        if(!u.isPresent())
        {
            User user = new User();
            user.setName("admin");
            user.setPassword(new BCryptPasswordEncoder().encode("admin"));
            user.getRoles().add(role);
            userReposiry.save(user);
        }

    }

    public void saveUser(User user)
    {
        String password = user.getPassword();
        if(!password.isEmpty())
        {
            user.setPassword(new BCryptPasswordEncoder().encode(password));
        }
        userReposiry.save(user);
    }



    @CacheEvict(cacheNames = "user",key = "#user.name")
    public void deleteUser(User user)
    {
        userReposiry.delete(user);
    }

    @Cacheable(cacheNames = "user",key = "#userName")
    public User getUser(String userName)
    {
        Optional<User> byId = userReposiry.findById(userName);
        if(byId.isPresent())
        {
            return byId.get();
        }
        return null;
    }









}
